package com.pig4cloud.pig.goods;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.pig4cloud.pig.common.feign.annotation.EnablePigFeignClients;
import com.pig4cloud.pig.common.security.annotation.EnablePigResourceServer;
import com.pig4cloud.pig.common.swagger.annotation.EnablePigSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.nio.charset.Charset;

@EnablePigSwagger2
@EnablePigResourceServer
@EnablePigFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class GoodsApp {
	public static void main(String[] args) {
		SpringApplication.run(GoodsApp.class,args);
	}

	@Bean("redisCacheTemplate")
	public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		redisTemplate.setKeySerializer(stringRedisSerializer);
		// redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		redisTemplate.setHashValueSerializer(new MyGenericJackson2JsonRedisSerializer());
		// redisTemplate.setHashValueSerializer(stringRedisSerializer);
		// redisTemplate.setDefaultSerializer(stringRedisSerializer);
		// redisTemplate.setEnableDefaultSerializer(true);
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

	class MyGenericJackson2JsonRedisSerializer extends GenericJackson2JsonRedisSerializer {

		public byte[] serialize(Object object) throws SerializationException {
			if (object == null) return new byte[0];
			if (object instanceof Long || object instanceof Double)
				return object.toString().getBytes(Charset.forName("UTF-8"));
			try {
				return JSON.toJSONBytes(object, SerializerFeature.WriteClassName);
			} catch (Exception exception) {
				throw new SerializationException("Could not serialize : " + exception.getMessage(), exception);
			}
		}
	}
}
